#!/bin/bash

# openGauss Performance Test Script
set -e

echo "Starting openGauss performance tests..."

# Set variables
DB_HOST=${DB_HOST:-127.0.0.1}
DB_PORT=5432
DB_USER="gaussdb"
DB_PASSWORD="OpenGauss@123"
DB_NAME="postgres"
RESULTS_DIR="/home/data/database/test_results"
mkdir -p $RESULTS_DIR

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OPENGAUSS_RESULT_FILE="$RESULTS_DIR/opengauss_perf_$TIMESTAMP.log"

echo "openGauss Performance Test - $TIMESTAMP" > $OPENGAUSS_RESULT_FILE
echo "========================================" >> $OPENGAUSS_RESULT_FILE

# Build psql command with password
export PGPASSWORD=$DB_PASSWORD
PSQL_CMD="psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME"

# Test connection
echo "Testing connection to openGauss..." | tee -a $OPENGAUSS_RESULT_FILE
if ! $PSQL_CMD -c "SELECT 1;" > /dev/null 2>&1; then
  echo "Error: Could not connect to openGauss" | tee -a $OPENGAUSS_RESULT_FILE
  echo "Please check if openGauss is running and accessible." | tee -a $OPENGAUSS_RESULT_FILE
  exit 1
fi

echo "Great! Successfully connected to openGauss" | tee -a $OPENGAUSS_RESULT_FILE

# Test 1: Basic connection and version
echo "1. Testing basic connection..." | tee -a $OPENGAUSS_RESULT_FILE
$PSQL_CMD -c "SELECT version();" >> $OPENGAUSS_RESULT_FILE 2>&1
echo "Basic connection test completed" | tee -a $OPENGAUSS_RESULT_FILE

# Test 2: Create test database and tables
echo "2. Creating test database and tables..." | tee -a $OPENGAUSS_RESULT_FILE
$PSQL_CMD -c "
CREATE DATABASE IF NOT EXISTS testdb;
" >> $OPENGAUSS_RESULT_FILE 2>&1

# Connect to test database
PSQL_TEST_CMD="psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d testdb"

$PSQL_TEST_CMD -c "
DROP TABLE IF EXISTS users;
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100),
  age INT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  user_id INT,
  amount DECIMAL(10,2),
  order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
" >> $OPENGAUSS_RESULT_FILE 2>&1

echo "Database and table creation completed" | tee -a $OPENGAUSS_RESULT_FILE

# Test 3: Data insertion performance
echo "3. Testing data insertion performance..." | tee -a $OPENGAUSS_RESULT_FILE
START_TIME=$(date +%s.%N)

# Insert sample data (1000 records) - using transaction for better performance
$PSQL_TEST_CMD -c "
BEGIN;
INSERT INTO users (name, email, age) 
SELECT 
  'user_' || seq, 
  'user_' || seq || '@example.com', 
  (20 + (random() * 50)::INT)
FROM generate_series(1, 1000) seq;
COMMIT;
" >> $OPENGAUSS_RESULT_FILE 2>&1

END_TIME=$(date +%s.%N)
INSERT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Insertion time for 1000 records: $INSERT_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Test 4: Query performance
echo "4. Testing query performance..." | tee -a $OPENGAUSS_RESULT_FILE

# Query 1: Simple COUNT
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "SELECT COUNT(*) FROM users;" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY1_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Count query time: $QUERY1_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Query 2: Conditional SELECT
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "SELECT * FROM users WHERE age > 30 LIMIT 10;" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY2_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Conditional query time: $QUERY2_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Query 3: JOIN query
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "
-- Insert some order data first
INSERT INTO orders (user_id, amount) 
SELECT id, (random() * 1000)::DECIMAL(10,2) 
FROM users LIMIT 100;

SELECT u.id, u.name, COUNT(o.id) as order_count 
FROM users u 
LEFT JOIN orders o ON u.id = o.user_id 
GROUP BY u.id, u.name 
LIMIT 5;
" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY3_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "JOIN query time: $QUERY3_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Query 4: Aggregation query
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "SELECT AVG(age) as avg_age, MAX(age) as max_age, MIN(age) as min_age FROM users;" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY4_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Aggregation query time: $QUERY4_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Test 5: Update performance
echo "5. Testing update performance..." | tee -a $OPENGAUSS_RESULT_FILE
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "UPDATE users SET age = age + 1 WHERE id <= 100;" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
UPDATE_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Update time for 100 records: $UPDATE_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Test 6: Complex query with window function (openGauss strength)
echo "6. Testing complex analytical query..." | tee -a $OPENGAUSS_RESULT_FILE
START_TIME=$(date +%s.%N)
$PSQL_TEST_CMD -c "
SELECT 
  id, 
  name, 
  age,
  AVG(age) OVER() as overall_avg_age,
  age - AVG(age) OVER() as age_diff_from_avg,
  ROW_NUMBER() OVER (ORDER BY age DESC) as age_rank
FROM users 
WHERE age IS NOT NULL
LIMIT 10;
" >> $OPENGAUSS_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
COMPLEX_QUERY_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Complex analytical query time: $COMPLEX_QUERY_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Test 7: Concurrent query test
echo "7. Testing concurrent queries..." | tee -a $OPENGAUSS_RESULT_FILE
START_TIME=$(date +%s.%N)
for i in $(seq 1 5); do
  $PSQL_TEST_CMD -c "SELECT COUNT(*) FROM users WHERE age > $((30 + i));" >> $OPENGAUSS_RESULT_FILE 2>&1 &
done
wait
END_TIME=$(date +%s.%N)
CONCURRENT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Concurrent query time: $CONCURRENT_TIME seconds" | tee -a $OPENGAUSS_RESULT_FILE

# Test 8: Resource usage
echo "8. Checking resource usage..." | tee -a $OPENGAUSS_RESULT_FILE
docker stats opengauss --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" >> $OPENGAUSS_RESULT_FILE 2>&1

# Test 9: Database statistics
echo "9. Checking database statistics..." | tee -a $OPENGAUSS_RESULT_FILE
$PSQL_TEST_CMD -c "
SELECT schemaname, tablename, tableowner, tablespace 
FROM pg_tables 
WHERE schemaname NOT LIKE 'pg_%' AND schemaname != 'information_schema';
" >> $OPENGAUSS_RESULT_FILE 2>&1

# Summary
echo "" >> $OPENGAUSS_RESULT_FILE
echo "Performance Test Summary" >> $OPENGAUSS_RESULT_FILE
echo "=======================" >> $OPENGAUSS_RESULT_FILE
echo "Insertion Performance: $INSERT_TIME seconds for 1000 records" >> $OPENGAUSS_RESULT_FILE
echo "Count Query: $QUERY1_TIME seconds" >> $OPENGAUSS_RESULT_FILE
echo "Conditional Query: $QUERY2_TIME seconds" >> $OPENGAUSS_RESULT_FILE
echo "JOIN Query: $QUERY3_TIME seconds" >> $OPENGAUSS_RESULT_FILE
echo "Aggregation Query: $QUERY4_TIME seconds" >> $OPENGAUSS_RESULT_FILE
echo "Complex Analytical Query: $COMPLEX_QUERY_TIME seconds" >> $OPENGAUSS_RESULT_FILE
echo "Update Performance: $UPDATE_TIME seconds for 100 records" >> $OPENGAUSS_RESULT_FILE
echo "Concurrent Queries: $CONCURRENT_TIME seconds for 5 queries" >> $OPENGAUSS_RESULT_FILE
echo "Test completed at: $(date)" >> $OPENGAUSS_RESULT_FILE

# Clean up
unset PGPASSWORD

echo ""
echo "openGauss performance test completed!"
echo "Results saved to: $OPENGAUSS_RESULT_FILE"